package com.csy.user.entity.system.service.impl;

import com.csy.commons.core.exception.CaptchaNotMatchException;
import com.csy.commons.core.exception.CustomException;
import com.csy.commons.core.utils.RedisCache;
import com.csy.commons.dto.LoginUser;
import com.csy.commons.framework.service.TokenService;
import com.csy.user.entity.system.service.SysLoginService;
import com.csy.user.utils.Constants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;


@Component
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;
    /*
     * 带验证码登录
     * */
    @Override
    public String login(String username, String password, String code, String uuid) {

        //1.从redis中获取验证码，判断是否正确
        String key = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(key);
        redisCache.deleteObject(key);

        if (captcha == null || !code.equalsIgnoreCase(captcha)){
            throw new CaptchaNotMatchException();
        }

        //2.进行用户认证
        Authentication authenticatation = null;
        try {
            authenticatation = authenticationManager.
                    authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }catch (Exception e){
            throw new CustomException(400,"用户不存在或密码错误！");
        }

        //3.获取用户经过身份验证的用户的主体信息
        LoginUser loginUser = (LoginUser) authenticatation.getPrincipal();

        return tokenService.createToken(loginUser);
    }


}
